package com.fita.wechat.web.controller;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.fita.entity.agent.Agent;
import com.fita.entity.agent.AgentApply;
import com.fita.entity.order.Order;
import com.fita.entity.wallet.TransactionRecord;
import com.fita.entity.wallet.UserWallet;
import com.fita.wechat.entity.search.SecondaryAgentOrderSearch;
import com.fita.wechat.entity.search.TransactionRecordSearch;
import com.fita.wechat.entity.security.Login;
import com.fita.wechat.service.*;
import com.fita.wechat.web.interceptor.Mobile;
import com.fita.wechat.web.resolver.Secure;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @description:
 * @author: 11200
 * @date: 2019/7/1
 */
@Controller
@RequestMapping(path = "/profile")
public class ProfileController {

    @Autowired
    private CouponService couponService;

    @Autowired
    private AgentService agentService;

    @Autowired
    private UserWalletService userWalletService;

    @Autowired
    private TransactionRecordService transactionRecordService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private AgentCompanyService agentCompanyService;

    /**
     *
     * @return
     */
    @RequestMapping("")
    @Mobile
    public ModelAndView profile(@Secure Login login) {
        ModelAndView modelAndView = new ModelAndView("profile/profile");

        Agent agent = agentService.load(login.getId());

        int couponNumber = couponService.countAvailableCoupons(login.getId());
        modelAndView.addObject("agent",agent);
        modelAndView.addObject("couponNumber",couponNumber);

        return modelAndView;
    }

    /**
     *
     * @return
     */
    @RequestMapping("/info")
    @Mobile
    public ModelAndView info(@Secure Login login) {

        ModelAndView modelAndView = new ModelAndView("profile/profile-info");

        Agent agent = agentService.load(login.getId());

        modelAndView.addObject("agent", agent);

        return modelAndView;
    }

    /**
     *
     * @return
     */
    @RequestMapping("/wallet")
    @Mobile
    public ModelAndView wallet(@Secure Login login,
                               Page page,
                               TransactionRecordSearch search) {

        ModelAndView modelAndView = new ModelAndView("profile/profile-wallet");

        UserWallet userWallet = userWalletService.createOrLoadByMobile(login.getMobile());

        modelAndView.addObject("userWallet", userWallet);
        
        search.addAgentId(login.getId());

        int count = transactionRecordService.count(TransactionRecord.class, search.getPreparedFilter(false));

        if (count > 0){
            List<TransactionRecord> transactionRecords = transactionRecordService.listByPage(TransactionRecord.class, search.getPreparedFilter(false), search.getOrder(), page.with(count));

            modelAndView.addObject("transactionRecords", transactionRecords);
        }
        return modelAndView;
    }

    @RequestMapping(path = "/transaction-records", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public HttpResult listTransactionRecord(@Secure Login login,
                                            Page page,
                                            TransactionRecordSearch search){

        HttpResult httpResult = new HttpResult();

        httpResult.success();

        UserWallet userWallet = userWalletService.createOrLoadByMobile(login.getMobile());

        search.addUserWalletId(userWallet.getId());

        int count = transactionRecordService.count(TransactionRecord.class, search.getPreparedFilter(false));

        if (count > 0){

            List<TransactionRecord> transactionRecords = transactionRecordService.listByPage(TransactionRecord.class, search.getPreparedFilter(false), search.getOrder(), page.with(count));

            httpResult.data("transactionRecords", transactionRecords);
        }
        return httpResult;
    };

    /**
     *
     * 二级代理列表
     *
     * @return
     */
    @RequestMapping("/secondary-agents")
    @Mobile
    public ModelAndView listSecondaryAgent(@Secure Login login) {

        ModelAndView modelAndView = new ModelAndView("profile/secondary-agent/secondary-agent-list");

        List<Agent> secondaryAgents = agentService.listSecondaryAgent(login.getId());

        modelAndView.addObject("secondaryAgents", secondaryAgents);

        return modelAndView;
    }

    /**
     * 招募二级代理
     * @return
     */
    @RequestMapping("/secondary-agents/recruit")
    @Mobile
    public ModelAndView recruit() {
        ModelAndView modelAndView = new ModelAndView("profile/secondary-agent/secondary-agent-recruit");
        return modelAndView;
    }

    /**
     * 招募二级代理生成页面
     * @param rate
     * @return
     */
    @RequestMapping(path = "/secondary-agents/create-recruit-poster")
    public ModelAndView createRecruitPoster(@Secure Login login, @RequestParam Long rate){

        ModelAndView modelAndView = new ModelAndView("profile/secondary-agent/secondary-agent-recruit-poster-create");

        modelAndView.addObject("rate", rate);

        modelAndView.addObject("primaryAgentId", login.getId());

        return modelAndView;
    }

    /**
     * 修改二级代理提成率
     *
     * @return
     */
    @GetMapping("/secondary-agents/{secondaryAgentId}/edit-commission-rate")
    @Mobile
    public ModelAndView changeSecondaryAgentCommissionRate(@PathVariable Long secondaryAgentId) {

        ModelAndView modelAndView = new ModelAndView("profile/secondary-agent/secondary-agent-commission-rate-edit");

        modelAndView.addObject("secondaryAgentId", secondaryAgentId);

        return modelAndView;
    }

    /**
     * 修改二级代理提成率
     * @param login
     * @param rate
     * @param secondaryAgentId
     * @return
     */
    @PatchMapping(value = "/secondary-agents/{secondaryAgentId}/edit-commission-rate", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    @Mobile
    public HttpResult onChangeSecondaryAgentCommissionRate(@Secure Login login,
                                                           @RequestParam Integer rate,
                                                           @PathVariable Long secondaryAgentId){
        try {
            agentService.changeSecondaryAgentCommissionRate(login.getId(), secondaryAgentId, rate);
            return new HttpResult().success();
        } catch (BusinessException e) {
            return new HttpResult().fail("500").message(e.getMessage());
        } catch (Exception e){
            return new HttpResult().fail("500");
        }
    }


    /**
     *
     * @return
     */
    @RequestMapping("/secondary-agents/{secondaryAgentId}")
    @Mobile
    public ModelAndView listSecondaryAgentOrder(@PathVariable Long secondaryAgentId,
                                                SecondaryAgentOrderSearch secondaryAgentOrderSearch,
                                                Page page) {

        ModelAndView modelAndView = new ModelAndView("profile/secondary-agent/secondary-agent-order-list");

        int count = orderService.count(secondaryAgentOrderSearch);

        if (count > 0){

            List<Order> orders = orderService.listByPage(Order.class, secondaryAgentOrderSearch.getPreparedFilter(false), secondaryAgentOrderSearch.getOrder(), page.with(count));

            modelAndView.addObject("orders", orders);
        }
        Agent agent = agentService.load(secondaryAgentId);

        modelAndView.addObject("agent", agent);

        return modelAndView;
    }

    @GetMapping(path = "/secondary-agents/{secondaryAgentId}/orders", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    @Mobile
    public HttpResult listSecondaryAgentOrder(Page page,
                                              SecondaryAgentOrderSearch secondaryAgentOrderSearch,
                                              @PathVariable Long secondaryAgentId) {
        HttpResult httpResult = new HttpResult();
        httpResult.success();

        secondaryAgentOrderSearch.bindSecondaryAgentId(secondaryAgentId);

        int count = orderService.count(Order.class, secondaryAgentOrderSearch.getPreparedFilter(false));
        if (count > 0){
            List<Order> orders = orderService.listByPage(Order.class, secondaryAgentOrderSearch.getPreparedFilter(false), secondaryAgentOrderSearch.getOrder(), page.with(count));
            httpResult.data("orders", orders);
        }
        return httpResult;
    }

    /**
     *
     * @return
     */
    @GetMapping("/withdraw")
    @Mobile
    public ModelAndView withdraw(@Secure Login login) {
        ModelAndView modelAndView = new ModelAndView("profile/profile-withdraw");
        UserWallet userWallet = userWalletService.createOrLoadByMobile(login.getMobile());
        modelAndView.addObject("userWallet", userWallet);
        return modelAndView;
    }

    /**
     *
     * 提现
     * @return
     */
    @PostMapping(path = "/withdraw", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Mobile
    @ResponseBody
    public HttpResult onWithdraw(@Secure Login login,
                                 @RequestParam Integer amount) {
        try {
            userWalletService.withdraw(login.getId(), amount);
            return new HttpResult().success();
        } catch (BusinessException e) {
            return new HttpResult().fail("500").message(e.getMessage());
        } catch (Exception e){
            return new HttpResult().fail("500");
        }
    }


    /**
     * 充值
     * @param login
     * @return
     */
    @GetMapping("/recharge")
    @Mobile
    public ModelAndView recharge(@Secure Login login) {
        ModelAndView modelAndView = new ModelAndView("profile/profile-recharge");
        UserWallet userWallet = userWalletService.createOrLoadByMobile(login.getMobile());
        modelAndView.addObject("userWallet", userWallet);
        return modelAndView;
    }


    /**
     * 充值
     * @param login
     * @param amount
     * @return
     */
    @PostMapping(path = "/recharge", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Mobile
    @ResponseBody
    public HttpResult onRecharge(@Secure Login login,
                                 @RequestParam Integer amount) {
        try {
            //userWalletService.withdraw(login.getId(), amount);
            return new HttpResult().success();
        } catch (BusinessException e) {
            return new HttpResult().fail("500").message(e.getMessage());
        } catch (Exception e){
            return new HttpResult().fail("500");
        }
    }



}
